<?php

namespace Biz\service\Store;

use Biz\model\store\StoreAsk;
use Biz\model\store\StoreAskLike;
use Biz\pockets\serviceTrait\_Async;
use Doraemon\model\ForbiddenWord\ForbiddenSceneWord as ForbiddenSceneWordModel;
use Doraemon\pockets\action\ApiAction;
use Doraemon\service\ForbiddenWord\ForbiddenSceneWord;
use Doraemon\service\Member;
use Doraemon\service\User;
use Exception;

/**
 * 门店问答
 * Class StoreAskService
 * @package Biz\service\Store
 */
class StoreAskService
{
    use _Async;

    public static function bGetMsgList($storeId, $page = 1, $pageSize = 20, $source = 'list')
    {
        if ($source == 'home') {
            $where = [
                'store_id' => $storeId,
                'LIMIT' => [($page - 1) * $pageSize, $pageSize],
                'ORDER' => [
                    'id' => 'DESC',
                ]
            ];
            $res = StoreAsk::getListByWhere($where);
            $uids = array_column($res, 'uid');
            $toUids = array_column($res, 'to_uid');
            $uids = array_merge($uids, $toUids);
            $uids = array_filter(array_unique($uids));
            $userInfos = User::getBatchBasicUserInfo($uids);
            $userInfos = array_column($userInfos, null, 'uid');
            unset($where['LIMIT']);
            unset($where['ORDER']);
            $count = StoreAsk::getCount($where);
            $list = [];
            foreach ($res as $row) {
                $list[] = [
                    'id' => $row['id'],
                    'uid' => $row['uid'],
                    'nick' => isset($userInfos[$row['uid']]) ? $userInfos[$row['uid']]['nick'] : '',
                    'avatar' => isset($userInfos[$row['uid']]) ? $userInfos[$row['uid']]['avatar'] : '',
                    'content' => $row['content'],
                    'addtime' => $row['addtime']
                ];
            }
        } else {
            $where = [
                'store_id' => $storeId,
                'pid' => 0,
                'LIMIT' => [($page - 1) * $pageSize, $pageSize],
                'ORDER' => [
                    'id' => 'DESC',
                ]
            ];
            $res = StoreAsk::getListByWhere($where);
            unset($where['LIMIT']);
            unset($where['ORDER']);
            $count = StoreAsk::getCount($where);
            $uids = [];
            foreach ($res as $key => $val) {
                $uids[] = $val['uid'];
                $uids[] = $val['to_uid'];
                $lastAnswer = StoreAsk::getInfoByWhere(['pid' => $val['id'], 'ORDER' => ['id' => 'DESC']]);
                $res[$key]['answer'] = !empty($lastAnswer) ? $lastAnswer : [];
            }
            $uids = array_unique(array_filter($uids));
            $userInfos = User::getBatchBasicUserInfo($uids);
            $userInfos = array_column($userInfos, null, 'uid');
            $list = [];
            foreach ($res as $row) {
                $info = [];
                if (empty($row['answer'])) {
                    $info['ask'] = [
                        'id' => $row['id'],
                        'uid' => $row['uid'],
                        'nick' => isset($userInfos[$row['uid']]) ? $userInfos[$row['uid']]['nick'] : '',
                        'avatar' => isset($userInfos[$row['uid']]) ? $userInfos[$row['uid']]['avatar'] : '',
                        'content' => $row['content'],
                        'like_num' => $row['like_num'],
                        'addtime' => $row['addtime']
                    ];
                } else {
                    $info['ask'] = [
                        'id' => $row['id'],
                        'uid' => $row['uid'],
                        'nick' => isset($userInfos[$row['uid']]) ? $userInfos[$row['uid']]['nick'] : '',
                        'avatar' => isset($userInfos[$row['uid']]) ? $userInfos[$row['uid']]['avatar'] : '',
                        'content' => $row['content'],
                        'like_num' => $row['like_num'],
                        'answer_num' => $row['answer_num'],
                        'addtime' => $row['addtime']
                    ];
                    $info['answer'] = [
                        'id' => $row['answer']['id'],
                        'uid' => $row['answer']['uid'],
                        'nick' => isset($userInfos[$row['answer']['uid']]) ? $userInfos[$row['answer']['uid']]['nick'] : '',
                        'avatar' => isset($userInfos[$row['answer']['uid']]) ? $userInfos[$row['answer']['uid']]['avatar'] : '',
                        'content' => $row['answer']['content'],
                        'like_num' => $row['answer']['like_num'],
                        'addtime' => $row['answer']['addtime']
                    ];
                }
                $list[] = $info;
            }
        }

        return ['list' => $list, 'total' => $count, 'is_over' => (($page * $pageSize) >= $count) ? 1 : 0];
    }

    public static function bGetAnswerList($storeId, $id, $page = 1, $pagSize = 20)
    {
        $result = [];
        $info = StoreAsk::getInfoByWhere(['store_id' => $storeId, 'id' => $id]);
        if ($info['pid'] == 0) {
            $askInfo = $info;
        } else {
            $askInfo = StoreAsk::getInfoByWhere(['store_id' => $storeId, 'id' => $info['pid']]);
        }
        if ($askInfo) {
            $askId = $askInfo['id'];
            $userInfo = User::getBasicUserInfo($askInfo['uid']);
            $result = [
                'id' => $askInfo['id'],
                'uid' => $askInfo['uid'],
                'nick' => $userInfo ? $userInfo['nick'] : '',
                'avatar' => $userInfo ? $userInfo['avatar'] : '',
                'question' => $askInfo['content'],
                'answer_num' => $askInfo['answer_num'],
                'like_num' => $askInfo['like_num'],
                'addtime' => $askInfo['addtime'],
                'answer_list' => [],
                'is_over' => 1,
                'total' => 0,
            ];
            $answerArr = StoreAsk::getListByWhere([
                'pid' => $askId,
                'LIMIT' => [($page - 1) * $pagSize, $pagSize],
                'ORDER' => ['id' => 'DESC']
            ]);
            if ($answerArr) {
                $answerIds = array_column($answerArr, 'id');
                $uids = array_column($answerArr, 'uid');
                $userInfos = User::getBatchBasicUserInfo($uids);
                $userInfos = array_column($userInfos, null, 'uid');
                $answerList = [];
                foreach ($answerArr as $row) {
                    $answerList[] = [
                        'id' => $row['id'],
                        'uid' => $row['uid'],
                        'nick' => isset($userInfos[$row['uid']]) ? $userInfos[$row['uid']]['nick'] : '',
                        'avatar' => isset($userInfos[$row['uid']]) ? $userInfos[$row['uid']]['avatar'] : '',
                        'answer' => $row['content'],
                        'addtime' => $row['addtime'],
                        'like_num' => $row['like_num']
                    ];
                }
                $count = StoreAsk::getCount(['pid' => $askId]);
                $result['answer_list'] = $answerList;
                $result['total'] = $count;
                $result['is_over'] = ($page * $pagSize) >= $count ? 1 : 0;
            }
        }
        return $result;
    }

    public static function addAsk($storeId, $storeUid, $uid, $question)
    {
        $remarkForbidden = new ForbiddenSceneWord(ForbiddenSceneWordModel::CONTENT, $question);
        if ($remarkForbidden->getHit() && !$remarkForbidden->getPublish()) {
            throw new Exception("内容中包含禁用词", ApiAction::CODE_ERROR_VIEW_TOSTA);
        }
        $data = [
            'pid' => 0,
            'store_id' => $storeId,
            'uid' => $uid,
            'to_uid' => $storeUid,
            'content' => $question,
        ];
        return StoreAsk::add($data);
    }

    public static function addAnswer($storeId, $askId, $uid, $toUid, $answer)
    {
        $remarkForbidden = new ForbiddenSceneWord(ForbiddenSceneWordModel::CONTENT, $answer);
        if ($remarkForbidden->getHit() && !$remarkForbidden->getPublish()) {
            throw new Exception("内容中包含禁用词", ApiAction::CODE_ERROR_VIEW_TOSTA);
        }
        $askInfo = StoreAsk::getInfoById($askId);
        if (empty($askInfo)) {
            throw new Exception('不存在的提问');
        }
        // 只有门店和提问者才能回答当前问题
        if ($askInfo['to_uid'] != $uid && $askInfo['uid'] != $uid) {
            throw new Exception('你暂无权限回答该提问');
        }
        $data = [
            'pid' => $askId,
            'store_id' => $storeId,
            'uid' => $uid,
            'to_uid' => $toUid,
            'content' => $answer,
        ];
        $answerId = StoreAsk::add($data);
        if ($answerId) {
            self::changeAskNum($answerId);
        }
        return $answerId;
    }

    public static function likeAnswer($answerId, $uid)
    {
        $answerInfo = StoreAsk::getInfoById($answerId);
        if (empty($answerInfo)) {
            throw new Exception('不存在的回答');
        }
        $askId = $answerInfo['pid'];
        $answerUid = $answerInfo['uid'];
//        if ($uid != $answerUid) {
        $data = [
            'ask_id' => $askId,
            'answer_id' => $answerId,
            'uid' => $uid,
            'like_status' => StoreAskLike::STATUS_NORMAL
        ];
        $likeInfo = StoreAskLike::getUserLikeInfo($uid, $answerId);
        if (empty($likeInfo)) {
            $result = StoreAskLike::add($data);
        } else {
            $result = StoreAskLike::updateData(['like_status' => StoreAskLike::STATUS_NORMAL], ['id' => $likeInfo['id']]);
        }
        if ($result) {
            self::changeAskNum($answerId);
        }
        return $result;
//        }
        return false;
    }

    public static function cancelLikeAnswer($answerId, $uid)
    {
        $result = false;
        $likeInfo = StoreAskLike::getUserLikeInfo($uid, $answerId);

        if ($likeInfo && $likeInfo['like_status'] == StoreAskLike::STATUS_NORMAL) {
            $result = StoreAskLike::updateData(['like_status' => StoreAskLike::STATUS_CANCEL], ['id' => $likeInfo['id']]);
            if ($result) {
                self::changeAskNum($answerId, false);
            }
        }
        return $result;
    }

    public static function changeAskNum($answerId, $changeTime = true)
    {
        $answerId ? self::_async($answerId, $changeTime) : false;
    }

    public static function _async_changeAskNum($answerId, $changeTime)
    {
        $info = StoreAsk::getInfoByWhere(['id' => $answerId]);
        if ($info) {
            $askId = $info['pid'];
            $answerNum = StoreAsk::getCount(['pid' => $askId]);
            $likeNum = StoreAskLike::getCount(['ask_id' => $askId]);
            $data = [
                'answer_num' => $answerNum,
                'like_num' => $likeNum,
                'edittime' => $changeTime ? date('Y-m-d H:i:s') : null
            ];
            StoreAsk::updateData($data, ['id' => $askId]);
        }
        $likeNum = StoreAskLike::getCount(['answer_id' => $answerId]);
        StoreAsk::updateData(['like_num' => $likeNum], ['id' => $answerId]);
    }

    /**
     * 获取问题列表
     * @param $store_id
     * @param string $field
     * @param int $offset
     * @return array
     */
    public static function getAskList($store_id, $field = '*', $offset = 3)
    {
        $where['pid'] = 0;
        $where['store_id'] = $store_id;
        $data['total'] = StoreAsk::getCount($where);
        $where['LIMIT'] = $offset;
        $where['ORDER'] = ['like_num' => "DESC", "id" => "DESC"];
        $data['list'] = StoreAsk::getListByWhere($where, $field);
        return $data;
    }


    /**
     * 门店问答列表页
     * @param int|string $store_id 门店id
     * @param int|string $page
     * @return array
     * @author liyuanwu
     */
    public static function storePagedList($store_id = 0, $page = 1)
    {
        $size = 20;
        $offset = $page > 1 ? ($page - 1) * $size : 0;
        $where = [
            'store_id' => $store_id,
            'pid' => 0,
        ];
        $orderWhere = [
            'ORDER' => [
                'like_num' => 'DESC',
                'addtime' => 'DESC',
            ],
            'LIMIT' => [
                $offset, $size
            ],
        ];

        $rs = StoreAsk::getListByWhere($where + $orderWhere);
        $total = StoreAsk::getCount($where);
        $is_over = $total > $page * $size ? 0 : 1;
        $list = [];
        $ids = empty($rs) ? [] : array_column($rs, 'id');
        $childMap = [];
        if (!empty($ids)) {
            $where = [
                'store_id' => $store_id,
                'pid' => $ids,
                'ORDER' => [
                    'addtime' => 'DESC',
                ],
            ];
            $child = StoreAsk::getListByWhere($where);
            foreach ($child as $v) {
                $childMap[$v['pid']][] = $v['content'];
            }
        }
        //格式化数据
        foreach ($rs as $v) {
            $list[] = [
                'question_id' => $v['id'],
                'question' => $v['content'],
                'answer' => empty($childMap[$v['id']]) ? '' : current($childMap[$v['id']]),
                'num' => $v['answer_num'],
            ];
        }

        return compact('is_over', 'list');
    }

    /**
     * 门店问答详情页
     * @param int $questionId 问题id
     * @param int $uid 用户id
     * @return array
     * @throws Exception
     * @author liyuanwu
     */
    public static function storeAskDetail($questionId = 0, $uid = 0)
    {
        $where = [
            'OR' => [
                'id' => $questionId,
                'pid' => $questionId,
            ],
            'ORDER' => [
                'id' => 'DESC'
            ],
        ];
        $list = StoreAsk::getListByWhere($where);

        if (empty($list)) throw new Exception('问题不存在');

        $uids = array_column($list, 'uid');
        $ids = array_column($list, 'id');
        $userInfo = Member::getUserInfoByUserIds($uids);
        $like = StoreAskLike::getListByWhere(['answer_id' => $ids, 'uid' => $uid, 'like_status' => StoreAskLike::STATUS_NORMAL]);
        $likeMap = empty($like) ? [] : array_column($like, null, 'answer_id');
        $response = [];
        $answer_list = [];
        foreach ($list as $v) {
            $user = $userInfo[$v['uid']] ?? [];
            if ($v['pid'] == 0) {
                $response += [
                    'store_id' => $v['store_id'],
                    'uid' => $v['uid'],
                    'question_id' => $v['id'],
                    'question' => $v['content'],
                    'addtime' => date("Y.m.d", strtotime($v['addtime'])),
                    'nick' => $user['nick'] ?? '',
                    'avatar_small' => $user['avatar_small'] ?? '',
                    'num' => $v['answer_num'],
                ];
            } else {
                $answer_list[] = [
                    'answer_id' => $v['id'],
                    'uid' => $v['uid'],
                    'nick' => $user['nick'] ?? '',
                    'avatar_small' => $user['avatar_small'] ?? '',
                    'answer' => $v['content'],
                    'addtime' => date("Y.m.d H:i:s", strtotime($v['addtime'])),
                    'like' => isset($likeMap[$v['id']]) ? 1 : 0,
                    'like_num' => $v['like_num'],
                ];
            }
        }

        return $response + ['answer_list' => $answer_list];
    }
}